﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using MediaStreamer.Containers;

namespace MediaStreamer
{
    public class TemplateHandler
    {
        private static string _baseTemplateDir = string.Format("{0}{2}{1}{2}", AppDomain.CurrentDomain.BaseDirectory,
                                                               "Templates", System.IO.Path.DirectorySeparatorChar);

        private static string popcornHourTemplateDir = _baseTemplateDir + "PopcornHour" + Path.DirectorySeparatorChar;
        private static string computerTemplateDir = _baseTemplateDir + "Computer" + Path.DirectorySeparatorChar;
        private static string mobileTemplateDir = _baseTemplateDir + "Mobile" + Path.DirectorySeparatorChar;

        public static byte[] PopulateTemplate(RequestInfo requestInfo, IEnumerable<MenuItem> items)
        {
            string currentPageTemplate;
            string currentBaseDir = null;
            PageTemplate pageTemplate = null;

            if (UserAgentHandler.IsPopcornHour(requestInfo))
            {
                currentBaseDir = popcornHourTemplateDir;
            }
            else if (UserAgentHandler.IsMobile(requestInfo))
            {
                currentBaseDir = mobileTemplateDir;
            }
            else
            {
                // show interface for unknown clients
                currentBaseDir = computerTemplateDir;
            }

            if (currentBaseDir == null)
                return Encoding.UTF8.GetBytes("<html><head><title>client identification error</title></head><body><h3>Client identification error.</h3><b>NO</b> template for your device has been found.</body></html>");

            switch (requestInfo.ResourceId)
            {
                case "/series/view":
                case "/series/season/view":
                case "/series/episode/view":
                    currentPageTemplate = currentBaseDir + requestInfo.ResourceId + Path.DirectorySeparatorChar;
                    pageTemplate = new PageTemplate(currentBaseDir, currentPageTemplate);
                    break;
                case "/":
                case "/movies":
                case "/series":
                case "/series/actors":
                case "/series/titles":
                case "/series/titles/ascending":
                case "/series/titles/descending":
                case "/series/genres":
                case "/series/status":
                case "/series/tags":
                case "/series/unseen":
                    currentPageTemplate = currentBaseDir;
                    pageTemplate = new PageTemplate(currentBaseDir, currentPageTemplate);
                    break;
            }


            if (pageTemplate == null)
                return Encoding.UTF8.GetBytes("<html><head><title>client identification error</title></head><body><h3>Client identification error.</h3><b>NO</b> template for your device has been found.</body></html>");

            var sb = new StringBuilder();
            sb.Append(PopulatePageTemplate(requestInfo, pageTemplate, items));

            sb.Replace("{TITLE}", requestInfo.ResourceId);
            sb.Replace("{CURRENTURL}", requestInfo.ResourceId + requestInfo.Query.AsString());

            // Make sure we hide all unused elements
            sb.Replace("{TOPMENU}", string.Empty);
            sb.Replace("{MENU}", string.Empty);
            sb.Replace("{LIST}", string.Empty);
            sb.Replace("{HEADER}", string.Empty);

            return Encoding.UTF8.GetBytes(sb.ToString());
        }

        private static string PopulatePageTemplate(RequestInfo requestInfo, PageTemplate pageTemplate, IEnumerable<MenuItem> items)
        {
            var sb = new StringBuilder(pageTemplate.Raw);
            foreach (var controlName in pageTemplate.Settings.Controls)
            {
                string controlContent = PopulateControl(requestInfo, controlName, pageTemplate.BaseDirectory, items);
                sb.Replace("{" + controlName + "}", controlContent);
            }
            return sb.ToString();
        }

        private static string PopulateControl(RequestInfo requestInfo, string controlName, string baseDir, IEnumerable<MenuItem> items)
        {
            var itemsForControl = items.Where(i => i.ElementId == controlName);

            var controlTemplate = new ControlTemplate(controlName, baseDir);
            var content = controlTemplate.PopulateControl(requestInfo, itemsForControl);

            return content;
        }

        public static byte[] PopulateStyle(RequestInfo requestInfo)
        {
            var sb = new StringBuilder();
            string currentTemplate = null;

            if (UserAgentHandler.IsPopcornHour(requestInfo))
            {
                currentTemplate = popcornHourTemplateDir + requestInfo.ResourceId + Path.DirectorySeparatorChar + "index.css";
            }
            else if (UserAgentHandler.IsMobile(requestInfo))
            {
                currentTemplate = mobileTemplateDir + requestInfo.ResourceId + Path.DirectorySeparatorChar + "index.css";
            }
            else
            {
                currentTemplate = computerTemplateDir + requestInfo.ResourceId + Path.DirectorySeparatorChar + "index.css";
            }

            if (string.IsNullOrEmpty(currentTemplate))
                return Encoding.UTF8.GetBytes("body { /* What you just did should qualify for http://failblog.org/. Please let them know... ;P */ }");

            // TODO: Make this call more safe ;)
            sb.Append(File.ReadAllText(currentTemplate));

            return Encoding.UTF8.GetBytes(sb.ToString());
        }

        public static byte[] PopulateImage(RequestInfo requestInfo)
        {
            string currentTemplate = null;

            if (UserAgentHandler.IsPopcornHour(requestInfo))
            {
                currentTemplate = popcornHourTemplateDir + requestInfo.ResourceId + Path.DirectorySeparatorChar +
                                  "index.jpg";
            }
            else if (UserAgentHandler.IsMobile(requestInfo))
            {
                currentTemplate = mobileTemplateDir + requestInfo.ResourceId + Path.DirectorySeparatorChar +
                                  "index.jpg";
            }
            else
            {
                currentTemplate = computerTemplateDir + requestInfo.ResourceId + Path.DirectorySeparatorChar + "index.jpg";
            }

            if (string.IsNullOrEmpty(currentTemplate))
                return new byte[] { };

            // TODO: Make this call more safe ;)
            return File.ReadAllBytes(currentTemplate);
        }

    }
}
